const { sleep, logger, SendSms, httpGet } = require('./util');
const { webLogin }    = require('./ti_logic_login');
const { goAndPay }    = require('./ti_logic_go_pay');
const { addCart }     = require('./ti_logic_add_cart');
const { preparePay }  = require('./ti_logic_prepare_pay');
const { openPuppeteer, closePuppeteer } = require('./ti_logic_puppeteer');
const { fetchTask } = require('./ti_config');

process.on('unhandledRejection', error => {
    //...不处理...
});

(async () => {
    while (1) {
        await sleep(1000);
        //读取有库存的规格
        let serial = 'TAS5548DCA';
        // try {
        //     const ret = JSON.parse(await httpGet(fetchTask));
        //     if (!ret.serial) continue;
        //     serial = ret.serial;
        // } catch(e) {
        //     continue;
        // }
        
        const page = await openPuppeteer();//打开浏览器
        global.page = page;//全局对象，方便调试

        logger('开始下单流程');

        const loginSucc = await webLogin(page);//登录
        if (!loginSucc) {
            await closePuppeteer();
            //登录失败，发送短信通知
            SendSms({
                TemplateId: '1169783',
            }, 'dev');
            continue;
        }

        //如果购物车里有商品，则先结算
        let orderedNum = 0;
        // const cartNum = await page.$('.ti_p-responsiveHeader-cart-count');
        // if (cartNum) {
        //     const txt = await page.evaluate(() => document.querySelector('.ti_p-responsiveHeader-cart-count').innerText);
        //     if (txt != '0') {
        //         orderedNum = Number(txt);
        //         logger('购物车里有'+orderedNum+'件商品，先结算');
        //     }
        // }
        // if (orderedNum <= 0) {
            orderedNum = await addCart(page, serial);//加购物车
            if (!orderedNum) {
                await closePuppeteer();
                continue;
            }
        // }

        if (!await preparePay(page)) {//支付前准备
            await closePuppeteer();
            continue;
        }

        if (!await goAndPay(page)) {//发起支付
            await closePuppeteer();
            continue;
        }

        logger('下单成功!');
        await closePuppeteer();
    }
})();
